package com.adingxiong.cft.util;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.adingxiong.cft.common.FileData;
import com.adingxiong.cft.constant.TempalteEnum;
import com.adingxiong.cft.errors.Assert;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @ClassName WordUtil
 * @Description  模版到处word工具类
 * @Author xiongchao
 * @Date 2020/11/9 15:17
 **/
@Component
public class WordUtil {



    /**
     *  本地开发没有问题   打包之后  生成word文档 打开显示 根架构XML数据无效的问题 (可能是编码格式问题 打开xml文件 里面有些字符显示的是 ????)
     * @param fileName
     * @param dataMap
     * @param response
     * @param request
     * @throws IOException
     */
    public void exportWordAsFl(String fileName, Map<String, Object> dataMap, HttpServletResponse response, HttpServletRequest request) throws IOException {
        //version 版本  根据自己xml引入的依赖版本需要一致
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("utf-8");
        //文件数据输出
        Writer out =null;
        //解决文件名因编码格式乱码的问题
        fileName = UnicodeUtil.toUtf8String(request,fileName);
        //设置文件为浏览器下载
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        //如果文件名为___或者一串字符 则是中文乱码导致的 需要进行转码或者格式规定
        //response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + fileName + "\"");
        //设置模版文件所在目录
        configuration.setClassForTemplateLoading(this.getClass(),"/templates/");
        //获取模版文件
        try {
            Template template = configuration.getTemplate("use-info-template.ftl");

            out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
            //合并文件和内容
            template.process(dataMap,out);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail("文件流转换异常");
        } catch (TemplateException e) {
            e.printStackTrace();
            Assert.fail("合并模版文件异常");
        } finally {
            if(out != null){
                out.close();
            }
        }
    }

    /**
     *  HWPFDocument  目前暂未调通 一直显示找不到某个方法的错误
     * @param fileName
     * @param dataMap
     * @param response
     * @param request
     * @throws IOException
     */
    public void exportWordAsPOI(String fileName, Map<String, Object> dataMap, HttpServletResponse response, HttpServletRequest request) throws IOException {
        TempalteEnum enums = TempalteEnum.getByType("repair");
        InputStream is = this.getClass().getResourceAsStream(enums.getFilePath());

        HWPFDocument document = null;

        try {
            document = new HWPFDocument(is);
            Range bodyRange = document.getRange();
            //替换内容
            for(Map.Entry<String,Object> entry: dataMap.entrySet()){
                bodyRange.replaceText("${" + entry.getKey() + "}", (String) entry.getValue());
            }

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            document.write(bs);
            FileData fileData = new FileData();
            fileData.setFileName(fileName);
            fileData.setBytes(bs.toByteArray());
            ExcelTools.setResponse(request,response,fileData);
            bs.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  使用 easypoi-base 框架  本地开发和服务器部署  测试均无问题
     * @param fileName
     * @param dataMap
     * @param response
     * @param request
     */
    public void exportWordAsEasy(String fileName, Map<String, Object> dataMap, HttpServletResponse response, HttpServletRequest request) throws IOException {
        XWPFDocument document = null;
        FileData data = null;
        TempalteEnum tempalteEnum = TempalteEnum.getByType("userInfo");
        try {

            document = WordExportUtil.exportWord07("templates/repair_report.docx",dataMap);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            document.write(os);
            os.flush();
            data = new FileData();
            data.setBytes(os.toByteArray());
            data.setFileName(tempalteEnum.getFileName());

            ExcelTools.setResponse(request,response,data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(document != null){
                document.close();
            }
        }
    }


}
